package ejb;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;

import model.Notification;

@Stateless
public class SendNotificationBean implements SendNotification {
	@Resource(mappedName="java:/ConnectionFactory")
	private ConnectionFactory cf;
	@Resource(mappedName="java:/queue/test")
	private Queue q;
	
	private Connection con;
	private Session ses;
	private MessageProducer mp;
	
	/**
     * Constructeur par defaut 
     */
	public SendNotificationBean(){	
	}
	
	@PostConstruct
    public void start(){
    	try{
			con = cf.createConnection();
			ses = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
			mp = ses.createProducer(q);
		}catch(JMSException e){
			e.printStackTrace();
		}
    }
    
    @PreDestroy
    public void close(){
    	try{
			ses.close();
			con.close();
		}catch(JMSException e){
			e.printStackTrace();
		}
    }
    /**
     * Permet d'envoyer une notification
     * @param n
     */
    public void send(Notification n){
    	try{
    		ObjectMessage notification = ses.createObjectMessage();
    		notification.setObject(n);
    		
    		mp.send(notification);
    	} catch(JMSException e){
			e.printStackTrace();
		}
    }
}
